package com.iweb.day12;

/**
 * @author WuYongheng
 * @date 2021/12/5
 * @description 多线程模拟抢票- 使用同步方法解决共享数据的安全问题
 */
public class TicketDemo1 implements Runnable {
    // 共享数据，票数信息
    private int count = 10;
    // 当前卖出的票数
    private int num = 0;
    // 标记是否有余票
    private boolean flag = true;

    @Override
    public void run() {
        // 若还有余票，就继续卖票

        while (flag) {
            sale();
            // 模拟网络延时
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        TicketDemo1 ticketDemo = new TicketDemo1();
        // 开启多个子线程
        Thread t1 = new Thread(ticketDemo);
        Thread t2 = new Thread(ticketDemo);
        Thread t3 = new Thread(ticketDemo);

        t1.setName("张三");
        t2.setName("代理");
        t3.setName("黄牛党");

        System.out.println("开始抢票啦！");

        t1.start();
        t2.start();
        t3.start();
    }

    /**
     * 自定义售票方法
     */
    private synchronized void sale() {
        if (count <= 0) {
            flag = true;
            return;
        }
        while (flag) {
            // 一直卖票知道卖完为止
            if (count <= 0) {
                break;
            }
            // 模拟买票，卖的票数增加，剩余的票数减少
            count--;
            num++;
            // 模拟网络延时
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            // 显示售票信息
            System.out.println(Thread.currentThread().getName()
                    + "抢到第" + num + "张票，剩余" + count + "张票！");
        }
    }

}
